<template>
  <view class="wrapper">
    <view class="main-wrapper">
      <scroll-view scroll-y class="left-menus">
        <template v-if="loading">
          <skeletonTag />
        </template>
        <template v-else>
          <view 
            :class="item.typeId === currentTag ? 'menu-item checked' : 'menu-item'" 
            v-for="item in tagList" 
            :key="item.typeId"
            @tap.stop="tagChange(item)"
          >
            <text class="txt">{{ item.typeName }}</text>
          </view>
        </template>
      </scroll-view>
      <view class="right-wrapper">
        <scroll-view scroll-y class="right-list" @scroll="scrollFunc">
          <view class="scorll-list">
            <template v-if="list && list.length > 0">
              <view class="product-box" v-for="product in list" :key="product.id">
                <FddProductItem :value="selected[product.id] ? selected[product.id].nums : 0" :step="product.numMin || 1" :item="product" @onChange="$event => productChange(product, $event)" />
              </view>
            </template>
            <template v-else-if="loading">
              <SkeletonProduct />
            </template>
            <template v-else>
              <xl-empty className="no-padding" empty-text="暂无商品" />
            </template>
          </view>
          <view class="fix-box"></view>
          <view class="service-btn-wrapper">
            <FddService :sendMessagePath="'/pages/index/index'" />
          </view>
        </scroll-view>
      </view>
    </view>
    <view class="footer">
      <view class="content">
        <view class="left">
          <view class="desc">合计: </view>
          <view class="price">¥ {{ amount }}</view>
        </view>
        <view v-if="login" @tap="verifyData" class="btn">确认支付</view>
      </view>
    </view>
  </view>
</template>
<script setup>
  import { ref, computed } from "vue";
  import { onLoad, onShow, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
  import { setStorage, getStorage } from "@/common/storage";
  import { showToast, isLogin, getWeiXinCode, wxLogin, todayIsLogin } from "@/common/util";
  import skeletonTag from "@/skeleton/skeleton-tag.vue";
  import FddProductItem from "@/components/fdd-product-item.vue";
  import xlEmpty from "@/components/xl-empty.vue";
  import SkeletonProduct from "@/skeleton/skeleton-product.vue"
  import dayjs from "dayjs";
  import FddService from "@/components/fdd-service.vue";

  const molds = 1; // 1: 非预定， 2：预定
  const containerId = ref("");
  // tag
  const tagList = ref([]);
  const loading = ref(true);
  const currentTag = ref("");
  // main
  const list = ref([]);
  const login = ref(isLogin());
  // 选中的商品
  const selected = ref({});
  const userInfo = ref({});

  const search = async () => {
    loading.value = true;
    try {
			const data = await uni.$request.get(uni.$api.commodityPage, {
				data: {
					molds, 
          containerId: containerId.value, // 货柜ID
				}
			});
      loading.value = false;
			tagList.value = data || [];
      if (tagList.value.length > 0) {
        currentTag.value = tagList.value[0].typeId;
        list.value = tagList.value[0].commodities || [];
      }
		} catch (error) {
      loading.value = false;
			console.error("error:", error);
		}
  }

  const scrollFunc = () => {

  }

  const tagChange = (tag) => {
    currentTag.value = tag.typeId;
    const curr = tagList.value.find(v => v.typeId === tag.typeId) || {};
    list.value = curr.commodities || [];
  }
  
  // 商品选择
  const productChange = (product, value) => {
    selected.value[product.id] = {
      ...product,
      nums: value
    };
  }

  // 总计
  const amount = computed(() => {
    return Number(Object.keys(selected.value).reduce((p, v) => {
      if (selected.value[v]) {
        const curr = selected.value[v];
        return p + (+(curr.reductions || curr.price) * +curr.nums)
      }
      return p;
    }, 0)).toFixed(2);
  });

  const resetData = () => {
		selected.value = {};
	}

  // 拼接参数
  const getParams = () => {
    let totals = 0;
		const commodities = [];
		Object.keys(selected.value).forEach(v => {
			if (selected.value[v] && selected.value[v].nums > 0) {
				const curr = selected.value[v];
				commodities.push({
					"commodityId": curr.id,
					"discounteds": +Number(curr.reductions * curr.nums).toFixed(2),
					"nums": curr.nums,
					"price": curr.price,
					"totals": +Number(curr.price * curr.nums).toFixed(2)
				});
				totals += (+curr.price * curr.nums);
			}
		})
    return {
      totals,
      commodities,
      containerId: containerId.value,
      molds,
      discounteds: amount.value
    }
  }
  // 支付订单
  const payOrder = (data = {}) => {
    wx.requestPayment({
      appId: data.appId,
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.packageVal,
      signType: data.signType,
      paySign: data.paySign,
      success: () => {
        resetData();
        uni.navigateTo({
          url: "/pages/orders/success?molds=1"
        });
      },
      fail: (error) => {
        console.log('error', error );
        showToast("支付失败!");
      }
    })
  }
  // 下单
  const placeOrder = async () => {
    const params = getParams();
    try {
			const data = await uni.$request.post(uni.$api.orderNewly, {
        isLoading: true,
				data: params
			});
			if (data.pays) {
        payOrder(data.pays);
      }
		} catch (error) {
			console.error("error:", error);
		}
  }
  // 校验商品
  const verifyData = () => {
    let nums = 0;
    Object.keys(selected.value).forEach((key) => {
      if (selected.value[key]) {
        nums += (selected.value[key].nums || 0);
      }
    });
    if (!(nums > 0)) {
      showToast("请选择商品");
      return;
    }
    if(isLogin()) {
      placeOrder();
    } else {
      getWeiXinCode((code) => {
        wxLogin(code, {containerId: containerId.value}).then((tokenObj) => {
          setStorage("token", tokenObj.tokenValue);
          login.value = true;
          placeOrder();
        });
      });
    }
  }

  const fetchUserInfo = async () => {
		try {
			const data = await uni.$request.get(uni.$api.customerInfo);
			userInfo.value = data || {};
		} catch (error) {
			console.error("error:", error);
		}
	}

  onShareAppMessage (() => {
		return {
      title: '点餐就免单！不玩套路！',
      path: `/pages/orders/index?userId=${userInfo.id}&containerId=${containerId.value}`
    }
	});
	onShareTimeline (() => {
		return {
      title: '点餐就免单！不玩套路！',
      path: `/pages/orders/index?userId=${userInfo.id}&containerId=${containerId.value}`
    }
	});

  onShow(() => {
    if (containerId.value) {
      search();
    }
    if (!todayIsLogin()) {
      getWeiXinCode((code) => {
        wxLogin(code, {containerId: containerId.value}).then((tokenObj) => {
          setStorage("token", tokenObj.tokenValue);
          setStorage("lastLoginTime", dayjs(new Date()).format("YYYY-MM-DD"));
          login.value = true;
          fetchUserInfo();
        });
      });
    } else {
      fetchUserInfo();
    }
  })
  onLoad((options) => {
	// || "480080634565061"
    const id = options.containerId || getStorage("containerId") || "480080634565061"
    if (id){
      setStorage("containerId", id);
      containerId.value = id;
    }
  });
  
</script>
<style lang="scss" scoped>
  .wrapper {
    width: 100%;
    height: 100vh;
    .main-wrapper {
      height: calc(100vh - 124upx);
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
      box-sizing: border-box;
      .left-menus {
        width: 166upx;
        height: 100%;
        padding-top: 30upx;
        box-sizing: border-box;
        .menu-item {
          width: 100%;
          height: 66upx;
          box-sizing: border-box;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          padding-left: 30upx;
          margin-top: 16upx;
          &:first-child {
            margin-top: 0;
          }
          .txt {
            color: #30302F;
            font-size: 30upx;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis;
          }
          &.checked {
            border-radius: 0px 100upx 100upx 0px;
            background: #E5E5E5;
            .txt {
              color: #30302F;
              font-size: 30upx;
              font-style: normal;
              font-weight: bold;
              line-height: normal;
            }
          }
        }
      }
      .right-wrapper {
        margin-left: 24upx;
        flex: 1;
        height: 100%;
        box-sizing: border-box;
        .right-list {
          width: 100%;
          height: 100%;
          padding-top: 20upx;
          box-sizing: border-box;
          .scorll-list { 
            border-radius: 23upx;
            background: #FFF;
            padding: 30upx;
            padding-right: 24upx;
            box-sizing: border-box;
            .product-box {
              padding-top: 30upx;
              padding-bottom: 30upx;
              border-top: 1upx solid #dbdbdb;
              &:first-child {
                padding-top: 0;
                border-top: none;
              }
              &:last-child {
                padding-bottom: 0;
              }
            }
          }
          .fix-box {
            width: 100%;
            height: 30upx;
          }
          .service-btn-wrapper {
            position: fixed;
            right: 0;
            bottom: 280upx;
            width: 100upx;
            height: 100upx;
            z-index: 1;
          }
        }
      }
    }
    .footer {
      width: 100%;
      height: 124upx;
      box-sizing: border-box;
      padding: 16upx 0;
      background-color: #FFF;
      .content {
        width: 690upx;
        margin-left: auto;
        margin-right: auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .left {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .desc {
            color: #1F1F1F;
            font-size: 30upx;
            font-style: normal;
            font-weight: 500;
            line-height: normal;
          }
          .price {
            color: #FF4D56;
            font-size: 38upx;
            font-style: normal;
            font-weight: 700;
            line-height: normal;
            margin-left: 30upx;
          }
        }
        .btn {
          width: 200upx;
          height: 90upx;
          border-radius: 100upx;
          background: #FF4D56;
          margin: 0;
          color: #FFF;
          font-size: 30upx;
          font-style: normal;
          font-weight: 600;
          line-height: 90upx;
          text-align: center;
        }
      }
    }
  }
</style>